/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.controller;

import com.vng.follow.client.FollowClient;
import com.vng.session.thrift.Session;
import com.vng.zing.stdprofile2.thrift.TValue;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.vng.zing.survey.model.CommonModel;
import com.vng.zing.survey.thrift.model.UserType;
import com.vng.zing.survey.utility.ZingMeService;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.Random;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public abstract class BaseController extends HttpServlet {
    
    protected enum ErrorType {
        
        SUCCESS,
        FAIL,
        ERROR_SYSTEM
    }
    private Logger logger = Logger.getLogger(this.getClass().getName());

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
      
        String out = "";
        try {
            out = render(request, response);
        } catch (Exception ex) {
             logger.error(ex.toString());
            out = showError("Đã có lỗi xảy ra. Vui lòng thử lại sau!" + ex.toString());
        }
        out(out, response);
    }
    
    protected String showError(String content) {
        try {
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonModel.getHeader(TemplateDictionary.create(), "Trang khảo sát"));
            dic.setVariable("FOOTER", CommonModel.getFooter(TemplateDictionary.create()));
            return CommonModel.getError(dic, content);
        } catch (Exception ex) {
            return "<h1>404 Not Found</h1>";
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        handle(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        handle(request, response);
    }
    
    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
           
            
            prepareHeader(resp);
            processRequest(req, resp);
        } catch (Exception ex) {
        }
    }
    
    protected abstract String render(HttpServletRequest request, HttpServletResponse resp) throws IOException, Exception;
    
    private void prepareHeader(HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        resp.addHeader("Server", "Zing Me Survey");
    }
    
    private void out(String content, HttpServletResponse respon) {
        PrintWriter out = null;
        try {
          
            
            out = respon.getWriter();
            out.print(content);
        } catch (Exception ex) {
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    
    protected String getName() {
        return this.getClass().getSimpleName();
    }
    
    protected String getKey(String[] value) {
        String key = getName();
        Arrays.sort(value);
        key += Arrays.toString(value);
        return key;
    }
    
    protected Map checkMember(HttpServletRequest request, UserType validUser) {
        try {
            Session session = ZingMeService.getSesstion(request);
            if (session == null) {
                return toHashMap(ErrorType.FAIL, "Bạn chưa đăng nhập!",-1, false,"");
            }
            //    check fanpage
            TValue fan = ZingMeService.getproflieUser(request.getParameter("fanpage"));
            if (fan == null || fan.getType() == 0) {
                return toHashMap(ErrorType.FAIL, "Fanpage không tồn tại",-1, false,"");
            }
            TValue user = ZingMeService.getproflieUser(session.getAccountName());
            // check user
            if (user == null) {
                return toHashMap(ErrorType.FAIL, "Không tìm thấy thông tin của bạn!",-1, false,"");
            }
            // check follow
            if (!FollowClient.getInstance().isFan(user.getUID(), fan.getUID()) && user.getUID() != fan.getUID()) {
                return toHashMap(ErrorType.FAIL, "Bạn không phải là thành viên của fanpage này!",-1, false,"");
            }
            boolean isAdmin = false;
            //check admin
            if (validUser.equals(UserType.ADMIN)) {
                if (user.getUID() != fan.getUID()) {
                    return toHashMap(ErrorType.FAIL, "Bạn không phải là Admin!", -1,false,"");
                } else {
                    isAdmin = true;
                }
            }
            else{
                if (user.getUID() == fan.getUID()) 
                    isAdmin=true;
            }
            return toHashMap(ErrorType.SUCCESS, fan.getUID(),user.getUID(), isAdmin,user.getDisplayName());
        } catch (Exception ex) {
            return toHashMap(ErrorType.ERROR_SYSTEM, "",-1, false,"");
        }
       
 
      

    }
    
    private Map toHashMap(ErrorType error, Object msg, int idUser, Boolean isAdmin, String name) {
        Map mapdata = new HashMap();
        mapdata.put("error", error);
        mapdata.put("msg", msg);
        mapdata.put("idUser", idUser);
        mapdata.put("admin", isAdmin);
        mapdata.put("name", name);
        return mapdata;
    }
}
